<?php
namespace Home\Controller;
use Think\Controller;
class ChooseLessonController extends Controller
{
    public function index()
    {
        $this->display('PrintLesson');
    }
    public function PrintLesson()//打印所有尚有余量的课程到模板
    {
        $lesson=M('totallesson')->where('leftvolume!=0')->select();
        $this->assign('lesson',$lesson);
        $this->display();
    }
    public function choose()
    {
        $n=0;
        $messages;
        if(cookie('student'))//判断学生是否登录
        {
            $student=$_SESSION['student'];//获取学生信息
            $ChooseLessons=$_POST['lesson'];//获取所选的所有课程代码
            foreach ($ChooseLessons as $ChooseLesson)//逐个课程添加
            {
                $Choose = M('totallesson')->where('lessonId=%d', $ChooseLesson)->select();//获取课程信息
                $Choose=$Choose[0];
                $selects = M('chooselesson')->where('studentId=%d', $student['studentid'])->select();//获取学生已选择的所有课程
                $flag=0;
                foreach ($selects as $temp)//判断当前所选课程和学生已选课程是否有时间冲突
                {
                    $select = M('totallesson')->where('lessonId=%d', $temp['lessonid'])->select();
                    $select=$select[0];
                    if (CommonController::equal($select['lessontime'], $Choose['lessontime']))
                        $flag=1;
                }
                if($flag==0)//写入学生选课表
                {
                    $write['lessonId'] = $Choose['lessonid'];
                    $write['studentId'] = $student['studentid'];
                    $write['teacherId'] = $Choose['teacherid'];
                    $temp=M('totallesson')->where('lessonId=%d',$write['lessonId'])->select();
                    if($temp[0]['leftvolume']>0)//再次判断当前课程是否还有余量，若有，写入选课表
                    {
                        $update['leftVolume'] =$temp[0]['leftvolume']-1;
                        $tip1 = M('totallesson')->where('lessonId=%d', $write['lessonId'])->save($update);
                        M('chooselesson')->create($write);
                        $tip2 = M('chooselesson')->add($write);
                        if ($tip1 && $tip2)
                            $messages[$n++] = '你已成功选择' . $Choose['lessonname'] . '课程';
                        else
                            $this->error('选课失败，请稍后再试', 'http://localhost/Nise-zf/index.php/Home/ChooseLesson/PrintLesson');
                    }

                }
            }
        }
        else
        {
            $this->error('你还没有登录，请登录','http://localhost/Nise-zf/index.php/Home/StudentLogin/index.html');
        }
        $this->success('选课完成，共成功选择了'.$n.'门课程','http://localhost/Nise-zf/index.php/Home/Student/page');
    }
}